package com.java.interview.reflect;

import org.junit.Test;

import java.lang.reflect.Field;

/**
 * Created by lyc on 2016-03-23.
 */
//java中有几种实例化方式？
//2种：一种直接new的方式另外一种利用java反射机制来实例化
//如何利用反射来修改类的私有属性？
public class InterviewReflect {

    @Test
    public void testNewInstantiation(){
        Apple apple=new Apple();
        org.junit.Assert.assertEquals(apple.getColor(),"red");//assertEquals比较字符串相等
    }
    @Test
    public void testReflectInstantiation() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
        // 实例化一个类
        Object apple=Class.forName(Apple.class.getName()).newInstance();
        System.out.println("APPLE:"+apple);//APPLE:com.java.interview.reflect.Apple@ae511
    }
    @Test
    public  void testUpdatePrivate() throws IllegalAccessException, NoSuchFieldException {
        //通过反射来修改私有变量
        Apple apple=new Apple();
        Class clazz=apple.getClass();
        Field field=clazz.getDeclaredField("color");
        field.setAccessible(true);
        field.set(apple,"green");
        System.out.println(apple.getColor());
    }
}
